<template>
    <div class="app-detail">
        <el-card class="box-card">
            <div class="container-header">
                <div class="hign-line"></div>
                <div class="header-left">
                    {{$t('inventoryManagement.baseInfo')}}
                </div>
            </div>
            <el-form :model="viewModel" ref="templateForm" label-width="88px" :rules="rules">
                <el-row :gutter="24" class="mb8">
                    <el-col :span="8">
                        <el-form-item :label="$t('inspectionManagement.templateName')" prop="templateName">
                            <el-input :disabled="isView||id" v-model="viewModel.templateName" :placeholder="
                      $t('public.placeholder', {
                        placeholder: $t('inspectionManagement.templateName'),
                      })
                    " clearable size="small" @keyup.enter.native="handleQuery" />
                        </el-form-item>
                    </el-col>

                    <el-col :span="8">
                        <el-form-item label="流程标识" prop="procKey" style="width:100%">
                            <el-select :disabled="isView||id" v-model="viewModel.procKey" :placeholder="$t('public.select_holder',{select_holder:'流程标识'})" style="width:100%;" filterable clearable size="small">
                                <el-option v-for="(item) in dict.type.NYIQC_PROCESS" :key="item.value" @click.native="changeKey(item)" :label="item.label" :value="item.value" />
                            </el-select>
                        </el-form-item>
                    </el-col>

                </el-row>

            </el-form>
        </el-card>
        <el-card class="box-card" style="margin-top:24px;height:450px">
            <div class="app-container">
                <div class="container-header">
                    <div class="hign-line"></div>
                    <div class="header-left">
                        流程引擎
                    </div>
                </div>
                <!-- <el-row :gutter="10" class="mb8">
                    <el-col :span="1.5">
                        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">{{$t('public.add')}}</el-button>
                    </el-col>
                </el-row> -->
                <div class="container-table">
                    <el-table border stripe v-loading="loading" :data="viewModel.handledList" @selection-change="handleSelectionChange">
                        <el-table-column type="index" label="序号" width="80" align="center" />
                        <!--          序号-->
                        <el-table-column label="步骤" align="center" prop="nodeName" width="110" />

                        <el-table-column label="人员" align="left" prop="projectName" minWidth="100">
                            <template slot-scope="scope">
                                <select-user-dialog v-model="scope.row.handledUserName" :disabled="isView" @sendData="(row) => userDataCallback(row,scope.$index)" />
                            </template>

                        </el-table-column>
                        <!--          项目类型-->
                        <el-table-column label="部门" align="left" prop="handledUserPedt" minWidth="100" />
                        <!--          检验项目名称-->
                        <el-table-column label="岗位" align="left" prop="handledUserPost" minWidth="100" />
                        <el-table-column :label="$t('public.opera')" fixed="right" align="center" width="100">
                            <template slot-scope="scope">
                                <div class="action-wrap">
                                    <table-body-btn type="add" @click.native="handleAdd(scope)" v-if="scope.row.jointlySignFlag==='1'&&!isView" />
                                    <table-body-btn type="delete" @click.native="handleDelete(scope)" v-if="scope.row.jointlySignFlag==='1'&&!isView" />
                                </div>
                            </template>
                        </el-table-column>
                    </el-table>

                </div>
            </div>
        </el-card>
        <div class="submit-footer">
            <el-button icon="el-icon-close" size="small" @click="closeTab" class="drawer-close">{{$t('public.close')}}</el-button>
            <el-button type="primary" @click="submitForm" icon="el-icon-check" size="small" v-if="!isView">{{$t('public.submit')}}</el-button>
        </div>
    </div>

</template>

<script>
import {getType, refreshCache} from '@/api/basic/dict/type'
import FileUploadInput from '@/components/FileUploadInput'
import MeasuringToolDialog from '@/views/components/MeasuringToolDialog'
import SelectUserDialog from '@/views/components/SelectUserDialog'
import {getNodeListByAppNameProcKey} from '@/api/inventoryManagement/ncrReview'
import {addTemplate, editTemplate, templateInfo,} from '@/api/flowTemplate/flowTemplate'

export default {
    name: 'addTemplate',
    dicts: ['NYIQC_PROCESS', 'NYIQC_CHECK_TYPE'],
    components: {
        FileUploadInput,
        MeasuringToolDialog,
        SelectUserDialog,
    },
    data() {
        return {
            direction: 'rtl',
            addInspectionExemption: false,
            unitList: [],
            drawer: false,
            approvalOpen: false,
            isView: false,
            viewInspectionExemption: false,
            addModel: {},
            viewModel: {
                handledList: [],
            },
            editModel: {},
            approvalForm: {
                status: '1',
                textarea: '',
            },
            templateName: decodeURIComponent(this.$route.params.id),
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            title: '',
            // 是否显示弹出层
            open: false,
            // 日期范围
            dateRange: [],
            projectList: [],
            // 查询参数
            queryParams: {
                pageNum: 1,
                pageSize: 10,
                noticeTitle: undefined,
                noticeType: undefined,
                hasRead: undefined,
                createTime: undefined,
            },
            // 表单参数
            form: {},
            // 表单校验
            rules: {
                templateName: [
                    {
                        required: true,
                        message: this.$t('formValidation.templateNameCannotBeEmpty'),
                        trigger: 'blur',
                    },
                ],
                procKey: [
                    {
                        required: true,
                        message: '流程标识不能为空',
                        trigger: 'change',
                    },
                ],
            },
            fullscreen: false,
        }
    },
    created() {
        this.getList()
        this.id = this.$route.params.id
        if (this.id) {
            templateInfo({ procKey: this.id }).then((response) => {
                this.viewModel = response.data
            })
        }
        if (this.$route.query.isView) {
            this.isView = true
        }
    },
    methods: {
        userDataCallback(row, index) {
            this.viewModel.handledList[index].handledUserPedt = row.deptName
            this.viewModel.handledList[index].handledUserPost = row.post
            this.viewModel.handledList[index].handledUserId = row.userId
        },
        changeKey() {
            this.getNodeListByAppNameProcKey()
        },
        getNodeListByAppNameProcKey() {
            getNodeListByAppNameProcKey({
                procKey: this.viewModel.procKey,
                appName: 'NYIQC',
            }).then((response) => {
                let userList = []
                response.data.forEach((io) => {
                    let obj = io
                    obj.nodeName = io.name
                    obj.nodeKey = io.key
                    obj.nodeVarName = io.varName
                    obj.jointlySignFlag = io.jointlySignFlag
                    userList.push(obj)
                })
                this.viewModel.handledList = userList
            })
        },
        checkoutTypeCopyFilter(row) {
            const current = this.dict.type.NYIQC_CHECK_TYPE.find((io) => {
                return io.value === row
            })
            return current ? current.label : ''
        },
        closeTab() {
            this.$router.push({
                path: '/flowTemplate',
            })
        },
        effectDateChange(e, scope) {
            if (parseInt(e) > 0) {
                this.viewModel.handledList[scope.$index].endDate =
                    this.getNewDay(scope.row.approvalTime, e)
            }
        },
        getNewDay(dateTemp, days) {
            var dateTemp = dateTemp.split('-')
            //转换为MM-DD-YYYY格式
            var nDate = new Date(
                dateTemp[1] + '-' + dateTemp[2] + '-' + dateTemp[0]
            )
            var millSeconds = Math.abs(nDate) + days * 24 * 60 * 60 * 1000
            var rDate = new Date(millSeconds)
            var year = rDate.getFullYear()
            var month = rDate.getMonth() + 1
            if (month < 10) month = '0' + month
            var date = rDate.getDate()
            if (date < 10) date = '0' + date
            return year + '-' + month + '-' + date
        },
        fileChange(e) {
            console.log(e)
        },
        drawerClose() {
            this.drawer = false
        },
        /** 查询字典类型列表 */
        getList() {
            // getNoticeList(this.queryParams).then((response) => {
            //     if (response.code == 200 && response.rows) {
            //         //   this.viewModel.handledList = response.rows;
            //         this.total = response.total
            //         this.loading = false
            //     }
            // })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            this.form = {
                dictId: undefined,
                dictName: undefined,
                dictType: undefined,
                status: '0',
                remark: undefined,
            }
            this.resetForm('form')
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNum = 1
            this.getList()
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.dateRange = []
            this.resetForm('queryForm')
            this.handleQuery()
        },
        /** 新增按钮操作 */
        handleAdd(scope) {
            let row = JSON.parse(JSON.stringify(scope.row))
            row.handledUserName = undefined
            row.handledUserPedt = undefined
            row.handledUserPost = undefined
            row.handledId = undefined
            this.viewModel.handledList.splice(scope.$index + 1, 0, row)
            // this.viewModel.handledList.push({
            //     nodeName: null,
            //     handledUserName: null,
            //     handledUserPedt: null,
            //     handledUserPost: null,
            // })
        },
        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.dictId)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        /** 修改按钮操作 */
        handleUpdate(row) {
            this.reset()
            const dictId = row.dictId || this.ids
            getType(dictId).then((response) => {
                this.form = response.data
                this.open = true
                this.title = '修改字典类型'
            })
        },
        /** 提交按钮 */
        submitForm: function () {
            this.$refs.templateForm.validate((valid) => {
                if (valid) {
                    if (this.id) {
                        editTemplate(this.viewModel).then((res) => {
                            this.loading = false
                            if (res.code == 200) {
                                this.$modal.msgSuccess('操作成功!')
                                this.$router.push({
                                    path: '/flowTemplate',
                                })
                            } else {
                                this.$modal.msgError(res.msg)
                            }
                        })
                    } else {
                        addTemplate(this.viewModel).then((res) => {
                            this.loading = false
                            if (res.code == 200) {
                                this.$modal.msgSuccess('操作成功!')
                                this.$router.push({
                                    path: '/flowTemplate',
                                })
                            } else {
                                this.$modal.msgError(res.msg)
                            }
                        })
                    }
                }
            })
        },
        /** 发起检验提交 */
        submitAddForm: function () {
            this.$modal.msgSuccess('发起成功!')
            this.addInspection = false
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            if (row.jointlySignFlag === '1') {
                this.$modal.msgWarning('请至少保留一条会签!')
                return
            }
            this.viewModel.handledList.splice(row.$index, 1)
        },
        /** 查看按钮操作 */
        handleView(row) {
            this.form = row
            this.viewInspectionExemption = true
            //   if(row.hasRead == 0){
            //     readNotice(row.noticeId).then(res=>{
            //       if(res.code == 200){
            //         this.handleQuery()
            //       }
            //     })
            //   }
        },
        /** 编辑按钮操作 */
        handleEdit(row) {
            this.drawer = true
        },
        /** 关闭抽屉操作 */
        handleClose(row) {
            this.drawer = false
        },
        /** 导出按钮操作 */
        handleExport() {
            this.download(
                'system/dict/type/export',
                {
                    ...this.queryParams,
                },
                `type_${new Date().getTime()}.xlsx`
            )
        },
        /** 刷新缓存按钮操作 */
        handleRefreshCache() {
            refreshCache().then(() => {
                this.$modal.msgSuccess('刷新成功')
            })
        },
    },
}
</script>
<style lang="scss" scoped>
::v-deep .el-card {
    padding-top: 20px;
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px;
    padding-bottom: 20px;
}
::v-deep .el-aside {
    padding: 0;
    margin-bottom: 0;
}
.content-style {
    border: 0px;
    box-shadow: 0px 2px 6px 0px rgba(0, 0, 0, 0.08);
    border-radius: 2px;
    background-color: white;
    margin-top: 10px;
}
::v-deep .el-button-group .selBtn {
    background: #fff;
    border: 1px solid #0b7be3;
    color: #0b7be3;
}
::v-deep .el-button-group .unselBtn {
    background: #fff;
    border: 1px solid #ededf2;
    color: #666666;
}
.header-left {
    float: left;
    font-size: 14px;
    font-family: PingFangSC-Semibold, PingFang SC;
    font-weight: 600;
    color: #333333;
    line-height: 40px;
    display: flex;
    justify-content: center;
}
.header-right {
    float: right;
}
.container-header {
    float: left;
    width: 100%;
    border-bottom: 1px solid #ededf2;
    padding-left: 12px;
}
.container-table {
    float: left;
    margin-top: 6px;
    width: 100%;
    max-height: calc(100vh - 600px);
    overflow: auto;
}
.mb8 {
    float: left;
    margin-top: 6px;
    width: 100%;
}
.drawer-footer {
    display: flex;
    position: relative;
    z-index: 9999;
    bottom: -40px;
    height: 40px;
    justify-content: center;
    width: 100%;
}
.hign-line {
    position: relative;
    left: -8px;
    top: 14px;
    height: 12px;
    border-radius: 2px;
    border: 1px solid #0b7be3;
    float: left;
}
.drawer-close {
    background: #f7f8fa;
    border-color: #f7f8fa;
}
.submit-footer {
    height: 52px;
    background: #ffffff;
    box-shadow: 0px -5px 5px 0px rgba(0, 0, 0, 0.08);
    border-radius: 4px 4px 0px 0px;
    position: fixed;
    z-index: 9;
    bottom: 0px;
    width: 100%;
    left: 0px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.samplingPercent {
    position: absolute;
    z-index: 9;
    right: 20px;
}
::v-deep .el-card {
    padding-top: 0px;
}
.app-detail {
    max-height: calc(100vh - 180px);
    overflow: auto;
}
</style>
